<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/10/16 09:51:24 $)
// $RCSfile: functions_wap.php,v $ : $Revision: 1.2 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Render the WAP ticket grid
*/
function renderWAPTicketGrid($ticketviewid, $departmentidlist, $ticketstatusidlist)
{
	global $dbCore, $_SWIFT, $datastore, $_fieldpointer, $template;

	ob_start();

	$_ticketview = &$_SWIFT["ticketviewcache"][$ticketviewid];
	if (!is_array($_ticketview))
	{
		trigger_error($_SWIFT["language"]["invalidview"], E_USER_ERROR);
	}

	$appendurl = "&amp;departmentid=". intval($_REQUEST["departmentid"]) ."&amp;ticketstatusid=". intval($_REQUEST["ticketstatusid"]);
	$_grid = $_update = array();
	$_gridset = &$_SWIFT["ticketgridcache"][$_SWIFT["staff"]["staffid"]];
	if (!is_array($_gridset))
	{
		$_gridset = array();
		$gridsetupdate = true;
	}

	$_staffid = &$_SWIFT["staff"]["staffid"];

	$_limit = $_ticketview["ticketsperpage"];
	if (!$_limit)
	{
		$_limit = "15";
	}
	$_grid[TICKETGRID_LIMIT] = intval($_limit);

	// Get the current offset for this page
	if (!empty($_REQUEST["offset"]) && is_numeric($_REQUEST["offset"]))
	{
		$_offset = intval($_REQUEST["offset"]);
	} else {
		$_offset = "0";
	}

	// Is sort order changed or is it default one? First we see if there is a custom sort order passed by user
	// just use the default sort order
	$_grid[TICKETGRID_SORTBY] = $_fieldpointer[$_ticketview["sortby"]]["name"];
	if (empty($_grid[TICKETGRID_SORTBY]))
	{
		$_grid[TICKETGRID_SORTBY] = $_fieldpointer[FIELD_LASTACTIVITY]["name"];
		$_update["sortby"] = FIELD_LASTACTIVITY;
	}
	$_grid[TICKETGRID_SORTORDER] = iif($_ticketview["sortorder"]==VIEW_ASC, "ASC", "DESC");

	// Build sort statement
	$sortstatement = iif($_grid[TICKETGRID_SORTBY], " ORDER BY ". $dbCore->escape($_grid[TICKETGRID_SORTBY]) .iif(strtolower($_grid[TICKETGRID_SORTORDER])=="desc", " DESC", " ASC"));

	$fields = $_customfieldidlist = array();
	$_findex = 0;

	/**
	* ###############################################
	* BUILD THE QUERIES
	* ###############################################
	*/
	$_sortjoin = $sortstatement." LIMIT ". intval($_offset) .", ". intval($_limit) .";";
	$ticketcount = 0;
	$_ticketidlist = array();
	$strdepartmentid = buildIN($departmentidlist);
	$strticketstatus = buildIN($ticketstatusidlist);
	$ojoinsql = array();
	unset($ownerjoin);
	if ($_ticketview["viewalltickets"] == 1)
	{
		// No Owner Join
	} else {
		if ($_ticketview["viewunassigned"] == 1) {
			$ojoinsql[] = "0";
		}
		if ($_ticketview["viewassigned"] == 1)
		{
			$ojoinsql[] = $_SWIFT["staff"]["staffid"];
		}
	}
	
	if (count($ojoinsql))
	{
		$ownerjoin = " AND `ownerstaffid` IN (". buildIN($ojoinsql) .")";
	}

	// ======= TICKET SEARCH TEST =======
	// First get the total tickets that fall under our criteria.
	$_ticketcnt = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."tickets` AS t WHERE t.departmentid IN (". $strdepartmentid .") AND t.ticketstatusid IN (". $strticketstatus .")". $ownerjoin .";");
	if (empty($_ticketcnt["totalitems"]))
	{
		$ticketcount = 0;
	} else {
		$ticketcount = intval($_ticketcnt["totalitems"]);
	}

	// Lets first get the total
	$_grid[TICKETGRID_TOTALITEMS] = $ticketcount;


	$gridurl = buildURL("index.php?_m=". $_SWIFT["currentmodule"] ."amp;_a=". $_SWIFT["currentaction"].$appendurl);

	// ======= START PAGINATION TABLE =======
	$_pagination = generate_pagination3($gridurl, $_grid[TICKETGRID_TOTALITEMS], $_limit, $_offset);

	$totalfields = count($fields)+1;
	$colspan = $totalfields;

	// ======= START GRID HEADER =======

	// ======= START GRID CONTENTS =======
	$dbCore->query("SELECT t.ticketid FROM `". TABLE_PREFIX ."tickets` AS t WHERE t.departmentid IN (". $strdepartmentid .") AND t.ticketstatusid IN (". $strticketstatus .")". $ownerjoin ." ". $_sortjoin .";");
	while ($dbCore->nextRecord())
	{
		$_ticketidlist[] = $dbCore->Record["ticketid"];
	}

	$strticketid = buildIN($_ticketidlist);
	$_tquery = "SELECT t.* FROM `". TABLE_PREFIX ."tickets` AS t WHERE t.ticketid IN (". $strticketid .") ". iif($usesearch==true, $_sortjoin, $sortstatement).";";

	echo $_pagination;
	$dbCore->query($_tquery, 2);
	$cnt = 0;
	while ($dbCore->nextRecord(2))
	{
		unset($record);
		unset($bgrecord);
		$cnt++;
		$id = $dbCore->Record2["ticketid"];
		$record = $dbCore->Record2;

		$record["overdue"] = false;
		if ($record["duetime"] != 0)
		{
			if (DATENOW >= $record["duetime"])
			{
				// Overdue
				$record["t.duetime"] = $_SWIFT["language"]["overdue"];
				$record["overdue"] = true;
			} else {
				$record["t.duetime"] = strColorDate(($record["duetime"]-DATENOW), true);
			}
		}
		$record["t.ticketid"] = iif($_SWIFT["settings"]["t_eticketid"]=="seq", intval($record["ticketid"]), $record["ticketmaskid"]);

		echo "<anchor>". htmlspecialchars($record["t.ticketid"]).": ".str_replace("\$", "", htmlspecialchars(strip_tags(stripslashes($record["subject"])))) ."<go href=\"". htmlspecialchars("index.php?_m=tickets&amp;_a=viewticket&amp;ticketid=". $record["ticketid"]) ."\"/></anchor><br/>\n";
	}

	$gridoutput = ob_get_contents();
	ob_end_clean();

	echo $gridoutput;
}


function generate_pagination3($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = FALSE)
{
	global $lang;
	//&offset=10

	$total_pages = ceil($num_items/$per_page);

	if( $total_pages == 1 )
	{
		return "";
	}

	$on_page = floor($start_item / $per_page) + 1;

	$page_string = "";

	if( $total_pages > 8 )
	{

		$init_page_max = ( $total_pages > 2 ) ? 2 : $total_pages;

		for($i = 1; $i < $init_page_max + 1; $i++)
		{
			$page_string .= ($i == $on_page) ? "<b>[$i]</b>" : "<anchor><go href=\"" . $base_url . "&amp;offset=" . ( ( $i - 1 ) * $per_page ) . "\"/>$i</anchor>";
			if( $i <  $init_page_max )
			{
				$page_string .= ", ";
			}
		}

		if( $total_pages > 2 )
		{
			if( $on_page > 1  && $on_page < $total_pages )
			{
				$page_string .= ( $on_page > 4 ) ? " ... " : ", ";

				$init_page_min = ( $on_page > 3 ) ? $on_page : 4;
				$init_page_max = ( $on_page < $total_pages - 3 ) ? $on_page : $total_pages - 3;

				for($i = $init_page_min - 1; $i < $init_page_max + 2; $i++)
				{
					$page_string .= ($i == $on_page) ? "<b>[$i]</b>" : "<anchor><go href=\"" . $base_url . "&amp;offset=" . ( ( $i - 1 ) * $per_page ) . "\"/>$i</anchor>";
					if( $i <  $init_page_max + 1 )
					{
						$page_string .= "&nbsp;";
					}
				}

				$page_string .= ( $on_page < $total_pages - 3 ) ? " ... " : ", ";
			}
			else
			{
				$page_string .= " ... ";
			}

			for($i = $total_pages - 1; $i < $total_pages + 1; $i++)
			{
				$page_string .= ($i == $on_page) ? "<b>[$i]</b>" : "<anchor><go href=\"" . $base_url . "&amp;offset=" . ( ( $i - 1 ) * $per_page ) . "\"/>$i</anchor>";
				if( $i <  $total_pages )
				{
					$page_string .= "&nbsp;";
				}
			}
		}
	}
	else
	{
		for($i = 1; $i < $total_pages + 1; $i++)
		{
				$page_string .= ($i == $on_page) ? "<b>[$i]</b>" : "<anchor><go href=\"" . $base_url . "&amp;offset=" . ( ( $i - 1 ) * $per_page ) . "\"/>$i</anchor>";
			if( $i <  $total_pages )
			{
				$page_string .= "&nbsp;";
			}
		}
	}

	$page_string  = "Pages($total_pages):" . " " . $page_string;
	return $page_string;
}
?>